﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using System.Globalization;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.ImportFarrowCommands
{
    public class ImportFarrowHandler : IRequestHandler<ImportFarrowCommand, Result>
    {
        //栋舍
        private readonly IBaseRepository<Cottages> cottagebaseRepository;
        //栏位
        private readonly IBaseRepository<Fields> fieldsRepository;
        //羊场
        private readonly IBaseRepository<SheepFarm> farmbaseRepository;
        //品种
        private readonly IBaseRepository<Variety> VarietybaseRepository;
        //基因等级
        private readonly IBaseRepository<GeneGrade> geneGradeRepository;
        //羊只类型
        private readonly IBaseRepository<SleepType> sleeptypebaseRepository;

        //档案信息
        private readonly IBaseRepository<SleepInfor> sleepinforbaseRepository;
        //出生状态
        private readonly IBaseRepository<BirthStatus> birthstatubaseRepository;
        //栋舍类型
        private readonly IBaseRepository<CottageType> cottageTypeRepository;



        public ImportFarrowHandler(IBaseRepository<Cottages> cottagebaseRepository, IBaseRepository<Variety> varietybaseRepository,
                                        IBaseRepository<GeneGrade> geneGradeRepository,
                                        IBaseRepository<Fields> fieldsRepository, IBaseRepository<FemaleBegin> femaleBeginRepository,
                                        IBaseRepository<SleepInfor> sleepinforbaseRepository,
                                        IBaseRepository<BirthStatus> birthstatubaseRepository, IBaseRepository<SheepFarm> farmbaseRepository,
                                        IBaseRepository<SleepType> sleeptypebaseRepository, IBaseRepository<CottageType> cottageTypeRepository)

        {
            this.cottagebaseRepository = cottagebaseRepository;
            this.VarietybaseRepository = varietybaseRepository;
            this.geneGradeRepository = geneGradeRepository;
            this.fieldsRepository = fieldsRepository;
            this.sleepinforbaseRepository = sleepinforbaseRepository;
            this.birthstatubaseRepository = birthstatubaseRepository;
            this.farmbaseRepository = farmbaseRepository;
            this.sleeptypebaseRepository = sleeptypebaseRepository;
            this.cottageTypeRepository = cottageTypeRepository;

        }
        public async Task<Result> Handle(ImportFarrowCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.search };
            //获取文件扩展名 判断上传的文件类型是否正确
            var ext = Path.GetExtension(request.file.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {

            }
            else
            {
                result.Messege = "您上传的文件类型不正确";
                return result;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                request.file.CopyTo(ms);
                ms.Position = 0;

                //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                //获取工作簿
                IWorkbook wb = null;
                if (ext == ".xls")//创建97-2003
                {
                    wb = new HSSFWorkbook(ms);
                }
                else//创建2007及以上版本
                {
                    wb = new XSSFWorkbook(ms);
                }
                //获取sheet 获取工作簿中的第一个工作表
                ISheet sheet = wb.GetSheetAt(0);

                int totalRows = sheet.LastRowNum;//总行数
                int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                // 创建一个用于存储解析后的数据的列表
                var farrowingsList = new List<SleepInfor>();

                //循环总行数 开头必须是1 不然从表头开始
                //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
                for (int i = 1; i <= totalRows; i++)
                {
                    //获取当前行
                    IRow row = sheet.GetRow(i);

                    //这个类必须写到循环里边 不然你批量添加只能添加一行
                    var dto = new SleepInfor();// 在循环内创建新的对象实例

                    //下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
                    var earnumber = row.GetCell(0).ToString();
                    var sleep = sleepinforbaseRepository.GetAll().Where(x => x.EarNumber == earnumber).FirstOrDefault();
                    dto.SleepInforId = sleep.SleepInforId;


                    //日期转换
                    //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                    string inputDate = row.GetCell(1).ToString();
                    string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                    DateTime parsedDate;
                    foreach (var format in multipleFormats)
                    {
                        if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                        {
                            dto.SleepBirthDate = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                            break;//成功解析后跳出循环
                        }
                    }
                    dto.VarietyId = Convert.ToInt32(row.GetCell(2).ToString());
                    dto.ElectronicEarTag = row.GetCell(3).ToString();
                    dto.GradeId = Convert.ToInt32(row.GetCell(4).ToString());
                    dto.Gender = row.GetCell(5).ToString() == "男" ? 1 : 0;
                    dto.SleepTypeId = Convert.ToInt32(row.GetCell(6).ToString());
                    dto.StayStatus = Convert.ToInt32(row.GetCell(7).ToString());
                    dto.FarmId = Convert.ToInt32(row.GetCell(8).ToString());
                    dto.RecordcottageId = Convert.ToInt32(row.GetCell(9).ToString());
                    dto.FieIdId = Convert.ToInt32(row.GetCell(10).ToString());
                    dto.FarEarNumber = row.GetCell(11).ToString();
                    dto.MoEarNumber = row.GetCell(12).ToString();
                    dto.SleepBirthPlace = row.GetCell(13).ToString();
                    dto.SleepBirthWeight =Convert.ToDecimal( row.GetCell(14).ToString());
                    dto.SleepNotes = row.GetCell(15).ToString();
                    dto.BirthdayId = Convert.ToInt32(row.GetCell(16).ToString());

                    //添加到数据集合中
                    farrowingsList.Add(dto);
                }
                //跳出循环后 使用AddRange进行批量添加
                var res =await sleepinforbaseRepository.AddRange(farrowingsList);
                //判断
                if (res > 0)
                {
                    result.Messege = "导入成功";
                }
                else
                {
                    result.Messege = "导入失败";
                }
                return result;
            }
        }
    }
}
